package org.theSeed.springDatasouceProp.config;

import cn.hutool.core.collection.CollectionUtil;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.theSeed.base.exp.ServiceExp;
import org.theSeed.base.utils.SeedStringUtil;
import org.theSeed.springDatasouceProp.contract.BaseDataSourceClose;
import org.theSeed.springDatasouceProp.pojo.SeedBaseDataSourceHolder;

import javax.annotation.PreDestroy;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * spring seed数据源配置
 */
@Slf4j
@Configuration
public class SpringDataSourceConfig {
    @Autowired
    private SeedBaseDataSourceHolder seedBaseDataSourceHolder;

    @Autowired(required = false)
    private List<BaseDataSourceClose> closeList;

    /**
     * 数据源关闭
     */
    @PreDestroy
    public void destry(){
        for (Map.Entry<String, DataSource> dsEntry : seedBaseDataSourceHolder.getSeedDataSourceProp().getDataSourceMap().entrySet()) {
            try {
                if (dsEntry.getValue() instanceof HikariDataSource){
                    ((HikariDataSource)(dsEntry.getValue())).close();
                }else if (dsEntry.getValue() instanceof HikariDataSource){
                    ((HikariDataSource)(dsEntry.getValue())).close();
                }else{
                    Boolean closeFlag = false;
                    if (CollectionUtil.isNotEmpty(closeList)){
                        for (BaseDataSourceClose baseDataSourceClose : closeList) {
                            if (baseDataSourceClose.canDoIt(dsEntry.getValue().getClass())){
                                baseDataSourceClose.closeDataSource(dsEntry.getValue());
                                closeFlag = true;
                                break;
                            }
                        }
                    }
                    if (!closeFlag){
                        throw new ServiceExp(SeedStringUtil.concatStr(dsEntry.getValue().getClass()+"数据源不支持关闭，请实现DataSourceClose"));
                    }
                }
                log.info("{}数据源已关闭",dsEntry.getKey());
            } catch (Exception e) {
                log.error("{}数据源关闭失败,信息为{}",dsEntry.getKey(),e.getMessage());
            }
        }
    }
}
